package com.security.lasys.agent.mainprocess;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
//    监听端口号
    public static final int PORT = 9999;
    private static ServerSocket serverSocket;

    private Socket socket;

    public static void main(String[] args) {
        System.out.println("服务器启动...\n");
        Server server = new Server();
    }

    public Server(){init();}

    /**
     * serverSocket 初始化
     */
    public void init(){
        try{
            if (serverSocket == null){
                serverSocket = new ServerSocket(PORT);
            }
        }catch (Exception e){
            System.out.println("服务器启动出现异常：" + e.getMessage());
        }
    }

    /**
     * 功能方法，被动打开
     *
     * @param message
     */
    public void sendEvent(String message){
        while(socket == null){
            //一旦堵塞，则表示服务器与客户端获得了连接
            try{
                socket = serverSocket.accept();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }

    /**
     * Runnable线程处理Socket
     */
    private class HandlerThread implements Runnable{

        private Socket socket;
        private String message = "";

        public HandlerThread(Socket client,String message){
            socket = client;
            this.message = message;
            new Thread(this).start();
        }


        public void run(){
            try{
                //向spark server端发送报警
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                out.writeBytes(message);
                out.flush();
                out.close();
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("服务器运行异常: " + e.getMessage());
            }finally {
                if (socket != null){
                    try{
                        socket.close();
                        socket = null;
                        message = "";
                    }catch (Exception e){
                        socket = null;
                        System.out.println("服务端finally异常："+e.getMessage());
                    }
                }
            }
        }
    }
}
